package com.youxue.controller;

import com.alibaba.fastjson.JSONObject;
import com.youxue.entity.Class;
import com.youxue.entity.*;
import com.youxue.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by 15c on 2018/1/27.
 */
@Controller

public class AdminController {

    @Autowired
    UserService userService;

    /**
     * 得到主页
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "admin/index";
    }


    /**
     * 得到登录页
     *
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String getLoginJsp() {
        return "admin/login";
    }

    /**
     * 处理登录提交的表单
     *
     * @param model               用于传error
     * @param httpServletRequest  用于获取表单参数
     * @param httpServletResponse 用于请求重定向
     * @param session             用于存用户的一些信息
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Model model, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpSession session) throws IOException {
        String uname = httpServletRequest.getParameter("uname");
        String password = httpServletRequest.getParameter("password");
        session.setAttribute("admin1", uname);
        if ("".equals(uname) || "".equals(password)) {
            String error = "用户名与密码不可以为空！";
            model.addAttribute("error", error);
            return "admin/login";
        }
        User checkUser = new User();
        checkUser.setUserEmail(uname);
        checkUser.setUserTelphone(uname);
        checkUser.setUserPassword(password);
        // 检查登录信息是否存在
        User resultUser = userService.selectUserIdByEmail(checkUser);
        if (null == resultUser) {
            resultUser = userService.selectUserIdByPhone(checkUser);
            if (null == resultUser) {
                String error = "登录失败，用户名或密码错误！";
                model.addAttribute("error", error);
                return "admin/login";
            } else if (resultUser.getUserPower() != 0 && resultUser.getUserPower() != 2) {
                String error = "登录失败，该账户不为管理员账户！";
                model.addAttribute("error", error);
                return "admin/login";
            } else if (resultUser.getUserStatus() != 0) {
                String error = "登录失败，该账户已被冻结！";
                model.addAttribute("error", error);
                return "admin/login";
            } else {
                session.setAttribute("admin", uname);
                //请求重定向
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/index");
            }
        } else if (resultUser.getUserPower() != 0 && resultUser.getUserPower() != 2) {
            String error = "登录失败，该账户不为管理员账户！";
            model.addAttribute("error", error);
            return "admin/login";
        } else if (resultUser.getUserStatus() != 0) {
            String error = "登录失败，该账户已被冻结";
            model.addAttribute("error", error);
            return "admin/login";
        } else {
            session.setAttribute("admin", uname);
            //存入当前登录用户权限
            session.setAttribute("power", resultUser.getUserPower());
            //请求重定向
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/index");
        }
        return null;

    }

    /**
     * 用于处理登出请求
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpSession session) throws IOException {
        session.removeAttribute("admin");
        session.removeAttribute("power");
        //请求重定向
//        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/index");
        return "admin/index";
    }

    /**
     * 用于查询所有用户
     *
     * @param model
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/admin/list", method = RequestMethod.GET)
    public String adminList(Model model, HttpServletRequest httpServletRequest, HttpSession session) {
        int pageOffset = 0;
        try {
            pageOffset = Integer.parseInt(httpServletRequest.getParameter("pager.offset"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        String admin = (String) session.getAttribute("admin");
        System.out.println("________________________________________admin" + admin);
        //通过（email、phone）查询管理员用户权限，给予相应管理用户列表
        User user = new User();
        user = userService.findUserByRetrieval(admin);
        //判断当前登录用户是否为超级用户
        if (user.getUserPower() == 2) {
            model.addAttribute("pager", userService.find(pageOffset));
            return "admin/list";
        } else {
            model.addAttribute("pager", userService.findByCommonAdmin(pageOffset));
            return "admin/list";
        }

    }

    /**
     * 用于关键字筛选用户（邮箱、电话、查找）
     *
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/admin/retrieval", method = RequestMethod.GET)
    public String retrievalStudents(HttpServletRequest httpServletRequest, Model model, String keyword, HttpSession session) {

        if (keyword.equals("")) {
            return "redirect:/students/list";
        } else {

            model.addAttribute("keyword", keyword);
            User user = userService.findUserByRetrieval(keyword);
            if (null == user) {
                return "admin/noRetrieval";
            }
            model.addAttribute("user", user);
            return "admin/user_retrieval";
        }
    }

    /**
     * 得到用户权限、状态更新页面
     *
     * @return
     */
    @RequestMapping(value = "/admin/update", method = RequestMethod.GET)
    public String getUpdateJsp(Model model, HttpServletRequest httpServletRequest) {
        int userId = 0;
        try {
            userId = Integer.parseInt(httpServletRequest.getParameter("userId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        User user = userService.findAUserInfo(userId);
        model.addAttribute("user", user);
        return "admin/user_update";
    }

    /**
     * 更新学生信息
     *
     * @return
     */
    @RequestMapping(value = "/admin/update", method = RequestMethod.POST)
    public String update(HttpSession session, User user) {
        System.out.println("-------------" + JSONObject.toJSONString(user));
        int result = userService.updateUser(user);
        if (result == 1) {
            session.setAttribute("type", "ok");
        } else {
            session.setAttribute("type", "error");
        }
        return "redirect:/admin/list";
    }

    @Autowired
    ClassService classService;

    /**
     * 查询课程列表（分页）
     *
     * @param httpServletRequest
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/classlist", method = RequestMethod.GET)
    public String ShowClassList(HttpServletRequest httpServletRequest, Model model) {
        int pageOffset = 0;
        try {
            pageOffset = Integer.parseInt(httpServletRequest.getParameter("pager.offset"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        Pager<Class> classList = classService.showListClass(pageOffset);
        model.addAttribute("pager", classList);
        return "admin/class_list";
    }

    @Autowired
    LineService lineService;

    /**
     * 查询线路列表
     *
     * @param httpServletRequest
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/linelist", method = RequestMethod.GET)
    public String ShowLineList(HttpServletRequest httpServletRequest, Model model) {
        int classId = 0;
        try {
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        List<Line> list = new ArrayList<Line>();
        list = lineService.showAClassAllLine(classId);
        if (list.size() == 0) {
            model.addAttribute("classId", classId);
            return "admin/noLine";
        } else {
            model.addAttribute("lineList", list);
            model.addAttribute("classId", classId);
            return "admin/line_list";
        }
    }

    @Autowired
    LineDetailService lineDetailService;

    /**
     * 查询一条路线所有景点
     *
     * @param httpServletRequest
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/linedetaillist", method = RequestMethod.GET)
    public String ShowLineDetailList(HttpServletRequest httpServletRequest, Model model) {
        int lineId = 0;
        int classId = 0;
        try {
            lineId = Integer.parseInt(httpServletRequest.getParameter("lineId"));
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }

        List<LineDetail> lineDetailList = new ArrayList<LineDetail>();
        lineDetailList = lineDetailService.showALineDetails(lineId);
        if (lineDetailList.size() == 0) {
            model.addAttribute("lineId", lineId);
            model.addAttribute("classId", classId);
            return "admin/noLineDetails";
        } else {
            model.addAttribute("lineDetailList", lineDetailList);
            model.addAttribute("lineId", lineId);
            model.addAttribute("classId", classId);
            return "admin/line_list_detail";
        }
    }

    /**
     * 删除一个线路景点
     *
     * @param httpServletRequest
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/delete/linedetail", method = RequestMethod.GET)
    public String DeleteLineDetail(HttpServletRequest httpServletRequest, Model model, HttpSession session) {
        int lineDetailId = 0;
        int lineId = 0;
        int classId = 0;
        try {
            lineDetailId = Integer.parseInt(httpServletRequest.getParameter("lineDetailId"));
            lineId = Integer.parseInt(httpServletRequest.getParameter("lineId"));
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        int result = lineDetailService.deleteALineDetail(lineDetailId);
        if (1 == result) {
            session.setAttribute("delete-type", "ok");

        } else {
            session.setAttribute("delete-type", "error");
        }
        return "redirect:/admin/linedetaillist?lineId=" + lineId + "&classId=" + classId;
    }

    @RequestMapping(value = "/admin/add/linedetail", method = RequestMethod.GET)
    public String getAddLineDetail(HttpServletRequest httpServletRequest, Model model, HttpSession session, LineDetail lineDetail) {
        int lineId = 0;
        int classId = 0;
        try {
            lineId = Integer.parseInt(httpServletRequest.getParameter("lineId"));
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        model.addAttribute("lineId", lineId);
        model.addAttribute("classId", classId);
        return "admin/line_detail_add";
    }

    /**
     * 添加一个景点
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @param lineDetail
     * @return
     */
    @RequestMapping(value = "/admin/add/linedetail", method = RequestMethod.POST)
    public String AddLineDetail(HttpServletRequest httpServletRequest, Model model, HttpSession session, LineDetail lineDetail) {
        int lineId = 0;
        int classId = 0;
        try {
            lineId = Integer.parseInt(httpServletRequest.getParameter("lineId"));
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        int result = lineDetailService.addALineDetail(lineDetail);
        if (1 == result) {
            session.setAttribute("add-type", "ok");
        } else {
            session.setAttribute("add-type", "error");
        }
        return "redirect:/admin/linedetaillist?lineId=" + lineId + "&classId=" + classId;
    }

    /**
     * 得到景点更新页面
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/update/linedetail", method = RequestMethod.GET)
    public String getUpdateLineDetail(HttpServletRequest httpServletRequest, Model model, HttpSession session) {
        int lineDetailId = 0;
        int lineId = 0;
        int classId = 0;
        try {
            lineId = Integer.parseInt(httpServletRequest.getParameter("lineId"));
            lineDetailId = Integer.parseInt(httpServletRequest.getParameter("lineDetailId"));
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        LineDetail lineDetail = new LineDetail();
        lineDetail = lineDetailService.showALineDetail(lineDetailId);
        model.addAttribute("lineDetail", lineDetail);
        model.addAttribute("lineId", lineId);
        model.addAttribute("lineDetailId", lineDetailId);
        model.addAttribute("classId", classId);
        return "admin/line_detail_update";
    }

    /**
     * 更新景点
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @param lineDetail
     * @return
     */
    @RequestMapping(value = "/admin/update/linedetail", method = RequestMethod.POST)
    public String updateLineDetail(HttpServletRequest httpServletRequest, Model model, HttpSession session, LineDetail lineDetail) {
        int lineId = 0;
        int classId = 0;
        try {
            lineId = Integer.parseInt(httpServletRequest.getParameter("lineId"));
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        int result = lineDetailService.updateALineDetail(lineDetail);
        if (1 == result) {
            session.setAttribute("update-type", "ok");
        } else {
            session.setAttribute("update-type", "error");
        }
        return "redirect:/admin/linedetaillist?lineId=" + lineId + "&classId=" + classId;
    }

    /**
     * 得到线路添加页面
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/add/line", method = RequestMethod.GET)
    public String getAddLine(HttpServletRequest httpServletRequest, Model model, HttpSession session) {
        int classId = 0;
        try {
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        model.addAttribute("classId", classId);
        return "admin/line_add";
    }

    /**
     * 添加一条路线
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @param line
     * @return
     */
    @RequestMapping(value = "/admin/add/line", method = RequestMethod.POST)
    public String addLine(HttpServletRequest httpServletRequest, Model model, HttpSession session, Line line) {
        int classId = 0;
        try {
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        int result = lineService.addLine(line);
        if (1 == result) {
            session.setAttribute("line-add-type", "ok");
        } else {
            session.setAttribute("line-add-type", "error");
        }
        model.addAttribute("classId", classId);
        return "redirect:/admin/linelist?classId=" + classId;

    }

    /**
     * 删除一条路线
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/delete/line", method = RequestMethod.GET)
    public String deleteLine(HttpServletRequest httpServletRequest, Model model, HttpSession session) {
        int lineId = 0;
        int classId = 0;
        try {
            lineId = Integer.parseInt(httpServletRequest.getParameter("lineId"));
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        //先删除该条路线下的所有景点，再删除该条路线
        try {
            lineDetailService.deleteALineDetailByLineId(lineId);
            int result = lineService.deleteLine(lineId);
            if (1 == result) {
                session.setAttribute("line-delete-type", "ok");
            } else {
                session.setAttribute("line-delete-type", "error");
            }
        } catch (Exception e) {
            session.setAttribute("line-delete-type", "error");
        } finally {
            return "redirect:/admin/linelist?classId=" + classId;
        }
    }

    /**
     * 得到线路修改页面
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/update/line", method = RequestMethod.GET)
    public String getUpdateLine(HttpServletRequest httpServletRequest, Model model, HttpSession session) {
        int classId = 0;
        int lineId = 0;
        try {
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
            lineId = Integer.parseInt(httpServletRequest.getParameter("lineId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        Line line = new Line();
        line = lineService.showALineInfo(lineId);
        model.addAttribute("line", line);
        model.addAttribute("classId", classId);
        return "admin/line_update";
    }

    /**
     * 更新路线
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @param line
     * @return
     */
    @RequestMapping(value = "/admin/update/line", method = RequestMethod.POST)
    public String updateLine(HttpServletRequest httpServletRequest, Model model, HttpSession session, Line line) {
        int classId = 0;
        try {
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        int result = lineService.updateALine(line);
        if (1 == result) {
            session.setAttribute("line-update-type", "ok");
        } else {
            session.setAttribute("line-update-type", "error");
        }
        return "redirect:/admin/linelist?classId=" + classId;

    }

    /**
     * 得到课程更新页面
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/update/class", method = RequestMethod.GET)
    public String GetUpdateClass(HttpServletRequest httpServletRequest, Model model, HttpSession session) {
        int classId = 0;
        try {
            classId = Integer.parseInt(httpServletRequest.getParameter("classId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        Class aclass = new Class();
        aclass = classService.showAClass(classId);
        System.out.println("-------------------------------------" + JSONObject.toJSONString(aclass));
        model.addAttribute("aclass", aclass);
        return "admin/class_update";
    }

    /**
     * 更新课程
     *
     * @param httpServletRequest
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/update/class", method = RequestMethod.POST)
    public String updateClass(HttpServletRequest httpServletRequest, Model model, HttpSession session, Class aclass) {

        int result = classService.updateAclass(aclass);
        System.out.println("------------------------------" + aclass.getClassState());
        if (1 == result) {
            session.setAttribute("class-update-type", "ok");
        } else {
            session.setAttribute("class-update-type", "error");
        }
        return "redirect:/admin/classlist";
    }

    /**
     * 用于关键字筛选用户（邮箱、电话、查找）
     *
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/admin/class/retrieval", method = RequestMethod.GET)
    public String retrievalClass(HttpServletRequest httpServletRequest, Model model, String keyword, HttpSession session) {

        int pageOffset = 0;

        try {
            pageOffset = Integer.parseInt(httpServletRequest.getParameter("pager.offset"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }


        if (keyword.equals("")) {
            return "redirect:/admin/classlist";
        } else {

            model.addAttribute("keyword", keyword);
            Pager<Class> pager = classService.findClassByRetrieval(keyword, pageOffset);
            if (pager.getDatas().isEmpty()) {
                return "admin/noClassRetrieval";
            }
            model.addAttribute("pager", pager);
            return "admin/class_retrieval";
        }
    }

    @Autowired
    ClassTypeService classTypeService;

    /**
     * 得到添加课程页面
     *
     * @param httpServletRequest
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/add/class", method = RequestMethod.GET)
    public String getAddClass(HttpServletRequest httpServletRequest, HttpSession session, Model model) {
        //查询阶段课程类型列表
        List<ClassType> classTypeList = new ArrayList<ClassType>();
        classTypeList = classTypeService.showAllRootClassType();
        model.addAttribute("firstType", classTypeList);
        return "admin/class_add";
    }

    /**
     * 课程添加
     *
     * @param httpServletRequest
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/add/class", method = RequestMethod.POST)
    public String addClass(HttpServletRequest httpServletRequest, HttpSession session, Class aclass) {
        int result = classService.addAclass(aclass);
        if (1 == result) {
            session.setAttribute("class-add-type", "ok");
        } else {
            session.setAttribute("class-add-type", "error");
        }
        return "redirect:/admin/classlist";
    }
    /**
     * form表单提交 Date类型数据绑定
     * <功能详细描述>
     * @param binder
     * @see [类、类#方法、类#成员]
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
    /**
     * 展示所有课程类型(根目录)
     *
     * @param httpServletRequest
     * @param session
     * @return
     */
    @RequestMapping(value = "/admin/show/type", method = RequestMethod.GET)
    public String showClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model) {
        List<ClassType> classTypeList = classTypeService.showAllRootClassType();
        model.addAttribute("classTypeList", classTypeList);
        return "admin/type_list";
    }

    /**
     * 得到根目录添加页面
     *
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/add/firstType", method = RequestMethod.GET)
    public String getAddRootClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model) {

        return "admin/root_type_add";
    }
    /**
     * 添加根目录页面
     *
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/add/firstType", method = RequestMethod.POST)
    public String addRootClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model,ClassType classType) {
        int result=classTypeService.addARootClassType(classType);
        if (1 == result) {
            session.setAttribute("rootType-add-type", "ok");
        } else {
            session.setAttribute("rootType-add-type", "error");
        }
        return "redirect:/admin/show/type";
    }

    /**
     * 得到更新课程根目录页面
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/update/firstType", method = RequestMethod.GET)
    public String getUpdateRootClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model) {
        int typeId = 0;
        try {
            typeId = Integer.parseInt(httpServletRequest.getParameter("typeId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        ClassType classType=classTypeService.showAClassType(typeId);
        model.addAttribute("classType", classType);
        return "admin/root_type_update";
    }
 /**
     * 更新课程根目录
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/update/firstType", method = RequestMethod.POST)
    public String updateRootClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model,ClassType classType) {
        int result=classTypeService.updateAClassType(classType);
        if (1 == result) {
            session.setAttribute("rootType-update-type", "ok");
        } else {
            session.setAttribute("rootType-update-type", "error");
        }
        return "redirect:/admin/show/type";
    }
    /**
     * 查询科目类型（secondType）
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/show/secondType", method = RequestMethod.GET)
    public String showClassSecondType(HttpServletRequest httpServletRequest, HttpSession session, Model model) {
        int typeId = 0;
        int pageOffset = 0;
        try {
            typeId = Integer.parseInt(httpServletRequest.getParameter("typeId"));
            pageOffset = Integer.parseInt(httpServletRequest.getParameter("pager.offset"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        Pager<ClassType> pager=new Pager<ClassType>();
        pager=classTypeService.showAllSecondClassTypeByPage(typeId,pageOffset);
        if (pager.getDatas().size()==0) {
            model.addAttribute("typeId", typeId);
            return "admin/type_second_list_no";
        }

        model.addAttribute("pager", pager);
        model.addAttribute("typeId", typeId);
        return "admin/type_second_list";
    }

    /**
     * 得到添加课程科目类型页面
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/add/secondType", method = RequestMethod.GET)
    public String getAddSecondClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model) {
        int pid = 0;
        try {
            pid = Integer.parseInt(httpServletRequest.getParameter("pid"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        model.addAttribute("pid", pid);
        return "admin/type_second_add";
    }
    /**
     * 得到添加课程科目类型页面
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/add/secondType", method = RequestMethod.POST)
    public String addSecondClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model,ClassType classType) {
        int pid = 0;
        try {
            pid = Integer.parseInt(httpServletRequest.getParameter("pid"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        int result=classTypeService.addARootClassType(classType);


        if (1 == result) {
            session.setAttribute("secondType-add-type", "ok");
        } else {
            session.setAttribute("secondType-add-type", "error");
        }
        model.addAttribute("pid", pid);
        return "redirect:/admin/show/secondType?typeId="+pid;
    }

    /**
     * 得到修改课程科目类型页面
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/update/secondType", method = RequestMethod.GET)
    public String getUpdateSecondClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model) {
        int typeId=0;
        try {
            typeId = Integer.parseInt(httpServletRequest.getParameter("typeId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        ClassType classType=classTypeService.showAClassType(typeId);
        model.addAttribute("classType", classType);
        model.addAttribute("pid", classType.getParentId());
        return "admin/type_second_update";
    }
    /**
     * 修改课程科目类型
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/update/secondType", method = RequestMethod.POST)
    public String getUpdateSecondClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model,ClassType classType) {
        int pid = 0;
        try {
            pid = Integer.parseInt(httpServletRequest.getParameter("pid"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        int result = classTypeService.updateAClassType(classType);


        if (1 == result) {
            session.setAttribute("secondType-update-type", "ok");
        } else {
            session.setAttribute("secondType-update-type", "error");
        }
        return "redirect:/admin/show/secondType?typeId=" + pid;
    }

    /**
     * 查询课程具体类型（thirdType）
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/show/thirdType", method = RequestMethod.GET)
    public String showClassThirdType(HttpServletRequest httpServletRequest, HttpSession session, Model model) {
        int pid = 0;
        int ppid = 0;
        int pageOffset = 0;
        try {
            pid = Integer.parseInt(httpServletRequest.getParameter("pid"));
            ppid = Integer.parseInt(httpServletRequest.getParameter("ppid"));
            pageOffset = Integer.parseInt(httpServletRequest.getParameter("pager.offset"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        Pager<ClassType> pager=new Pager<ClassType>();
        pager=classTypeService.showAllSecondClassTypeByPage(pid,pageOffset);
        if (pager.getDatas().size()==0) {
            model.addAttribute("pid", pid);
            model.addAttribute("ppid", ppid);
            return "admin/type_third_list_no";
        }

        model.addAttribute("pager", pager);
        model.addAttribute("pid", pid);
        model.addAttribute("ppid", ppid);
        return "admin/type_third_list";
    }

    /**
     * 得到修改课程具体类型页面
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/update/thirdType", method = RequestMethod.GET)
    public String getUpdateThirdClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model) {
        int typeId=0;
        try {
            typeId = Integer.parseInt(httpServletRequest.getParameter("typeId"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        ClassType classType=classTypeService.showAClassType(typeId);
        model.addAttribute("classType", classType);
        model.addAttribute("pid", classType.getParentId());
        return "admin/type_third_update";
    }
    /**
     * 修改课程具体类型
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/update/thirdType", method = RequestMethod.POST)
    public String getUpdateThirdClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model,ClassType classType) {
        int pid=0;
        try {
            pid = Integer.parseInt(httpServletRequest.getParameter("pid"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        int result=classTypeService.updateAClassType(classType);

        if (1 == result) {
            session.setAttribute("thirdType-update-type", "ok");
        } else {
            session.setAttribute("thirdType-update-type", "error");
        }
        return "redirect:/admin/show/thirdType?pid=" + pid;
    }

    /**
     * 得到添加课程具体类型页面
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/add/thirdType", method = RequestMethod.GET)
    public String getAddThirdClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model) {
        int pid = 0;
        int ppid = 0;
        try {
            pid = Integer.parseInt(httpServletRequest.getParameter("pid"));
            ppid = Integer.parseInt(httpServletRequest.getParameter("ppid"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        model.addAttribute("pid", pid);
        model.addAttribute("ppid", ppid);
        return "admin/type_third_add";
    }
    /**
     * 添加课程具体类型
     * @param httpServletRequest
     * @param session
     * @param model
     * @return
     */
    @RequestMapping(value = "/admin/add/thirdType", method = RequestMethod.POST)
    public String addThirdClassType(HttpServletRequest httpServletRequest, HttpSession session, Model model,ClassType classType) {
        int pid = 0;
        try {
            pid = Integer.parseInt(httpServletRequest.getParameter("pid"));
        } catch (NumberFormatException e) {
            e.getMessage();
        }
        int result=classTypeService.addARootClassType(classType);


        if (1 == result) {
            session.setAttribute("thirdType-add-type", "ok");
        } else {
            session.setAttribute("thirdType-add-type", "error");
        }
        model.addAttribute("pid", pid);

        return "redirect:/admin/show/thirdType?pid="+pid;
    }

    /**
     * 课程图片上传入口
     *
     * @param request 用户请求
     * @param image   图片
     * @return 结果json
     */
    @ResponseBody
    @RequestMapping(value = "/class/image-upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String imageUpload(HttpServletRequest request, @RequestParam(required = false) String image) {
        System.out.println("image为：" + image + " end " );
        ErrorJsonObject errorJsonObject;
        //指定头类型
        String headerPng = "data:image/png;base64,";
        String headerJpG = "data:image/jpeg;base64,";

        //获取服务器的路径
        String realPath = request.getSession().getServletContext().getRealPath("/resources/classImg");

        System.out.println("realPath为：" + realPath + "  end");
        //声明图片地址
        String imgAddress = null;
        //获取扩展名
        String extensionName = ".png";
        System.out.println("--------------- >" + extensionName);
        if (image != null && (image.indexOf(headerPng) != 0 || image.indexOf(headerJpG) != 0)) {
            String headPng = image.substring(0,  headerPng.length());
            String headJpG = image.substring(0, headerJpG.length());
            if (headerJpG.equals(headJpG)) {
                //去掉头部
                image = image.substring(headerJpG.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject(" 上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else if (headerPng.equals(headPng)) {
                //去掉头部
                image = image.substring(headerPng.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject(" 上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, " 上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else {
                errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
                return errorJsonObject.toJSONString();
            }
        } else {
            errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
            return errorJsonObject.toJSONString();
        }
    }

    /**
     * 景点图片上传入口
     *
     * @param request 用户请求
     * @param image   图片
     * @return 结果json
     */
    @ResponseBody
    @RequestMapping(value = "/line/image-upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String LineDetailImageUpload(HttpServletRequest request, @RequestParam(required = false) String image) {
        System.out.println("image为：" + image + " end " );
        ErrorJsonObject errorJsonObject;
        //指定头类型
        String headerPng = "data:image/png;base64,";
        String headerJpG = "data:image/jpeg;base64,";

        //获取服务器的路径
        String realPath = request.getSession().getServletContext().getRealPath("/resources/lineImg");

        System.out.println("realPath为：" + realPath + "  end");
        //声明图片地址
        String imgAddress = null;
        //获取扩展名
        String extensionName = ".png";
        System.out.println("--------------- >" + extensionName);
        if (image != null && (image.indexOf(headerPng) != 0 || image.indexOf(headerJpG) != 0)) {
            String headPng = image.substring(0,  headerPng.length());
            String headJpG = image.substring(0, headerJpG.length());
            if (headerJpG.equals(headJpG)) {
                //去掉头部
                image = image.substring(headerJpG.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功 ！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else if (headerPng.equals(headPng)) {
                //去掉头部
                image = image.substring(headerPng.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject(" 上传成功 ！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, " 上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else {
                errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
                return errorJsonObject.toJSONString();
            }
        } else {
            errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
            return errorJsonObject.toJSONString();
        }
    }

}
